# coding:utf-8
# coder:DongLing

import socket

host = '127.0.0.1'
port = 9008

# # 1.基于tcp协议socket套接字编程半双工模式服务器端
#
# s = socket.socket()
# s.bind((host, port))
# s.listen(5)
#
# # 添加循环
# while 1:
#     conn, addr = s.accept()
#
#     while 1:
#         content = conn.recv(1024)
#         if len(content) is 0:
#             print('接受到客户端数据为空')
#         else:
#             print('接受客户端发送来的数据为%s' % content.decode('utf-8'))
#             result = input('请输入要返回给客户端的数据:')
#             conn.send(result.encode('utf-8'))
#     conn.close()
# s.close()

import socketserver
from socketserver import StreamRequestHandler as srh

# 2.socketserver异步非阻塞编程,编写代码 --> 服务器端
addr = (host, port)
s = socket.socket()


# 需要自定义请求处理类，并实现父类方法handle
class Server(srh):  # 自定义类必须继承srh(別名)
    # 处理请求的方法
    def handle(self):
        print('连接到服务器的客户端地址为%s:' % str(self.client_address))
        while 1:
            content = self.request.recv(1024)
            if not content:
                break
            print('服务器接收的数据为%s' % content.decode('utf-8'))
            # 处理数据
            result = input('请输入返回给客户端的数据:')
            self.request.send(result.encode('utf-8'))


# 开启服务器
print('开始处理请求:')
# 构造一个多线程tcp

server = socketserver.ThreadingTCPServer(addr, Server)  # 异步通信机制
server.serve_forever()  # 开启
